package com.money.consumption;

import com.common.rabitmq.RabbitmqName;
import com.money.service.PayService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;


//支付  处理订单
@Component
@Slf4j
public class PayConsumption {

    @Autowired
    private PayService payService;

    @RabbitListener(queues = {RabbitmqName.rapid_pay})
    public void Pay(Message message, Channel channel) {
        String ctId = new String(message.getBody());

        ArrayList<Integer> ids = stringToIntArr(ctId);

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //开启手动模式
            channel.confirmSelect();
            payService.payOrder(ids);
            //设置确认
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            //出现异常我们就 取消确认
            try {
                channel.basicNack(deliveryTag, false, true);
            } catch (IOException ioException) {
                //出现入队列出现异常 我们就打印异常
                log.error(ioException.getMessage() + ":rabbitmq 重新返回队列失败！");
            }
        }

    }


    /**
     * 将String字符串转换为int数组（数字范围0-9）
     *
     * @param str 字符串（内只能包含数字0-9）
     * @return 字符串内产生的数组
     */
    public static ArrayList<Integer> stringToIntArr(String str) {
        String[] split = str.replace("[", "").replace("]", "").split(",");
        ArrayList<Integer> ids = new ArrayList<>();
        for (String id : split) {
            ids.add(Integer.parseInt(id));
        }
        return ids ;
    }

}
